/**     
 * @{#} CommandFireListenter.java Create on 2011-7-22 下午12:17:20     
 *     
 * Copyright (c) 2011 by xiaofeng.zhouxf     
 */
package com.sefer.memcached.lifecycle;

import java.io.IOException;
import java.util.List;

import com.sefer.memcached.command.Command;
import com.sefer.memcached.connect.Connector;
import com.sefer.memcached.connect.SocketWrap;
import com.sefer.memcached.connectpool.ConnectPool;
import com.sefer.memcached.constants.ErrorCode;
import com.sefer.memcached.constants.LifeEventInfo;
import com.sefer.memcached.exception.ClientException;

/**
 * @author <a href="mailto:xiaofeng.zhouxf83@gmail.com">xiaofeng.zhouxf</a>
 * @version 1.0
 */
public class CommandFireListenter implements LifeListener {
	private ConnectPool pool;

	@Override
	public boolean fireEvent(LifeEvent event) {
		if (event != null && LifeEventInfo.CALL_SERVER == event.getEventInfo()) {
			Command command = event.getCommand();
			Connector connector = pool.getConnector(command.getKey());
			String retStr = callServer(command);
			if (!command.validateResult(retStr)) {
				throw new ClientException(ErrorCode.E_301, command.getName()
						+ " data faild");
			}
			command.setResult(retStr);
		}
		return false;
	}

	public ConnectPool getPool() {
		return pool;
	}

	public void setPool(ConnectPool pool) {
		this.pool = pool;
	}

	public String callServer(Command command) {

		Connector connector = pool.getConnector(command.getKey());
		SocketWrap sock = connector.getSocketWrap();
		sock.write(command.generateCommand().getBytes());
		if (command.getMessage() != null) {
			sock.write(command.getMessage().getBytes());
			sock.write("\r\n".getBytes());
		}
		sock.flush();
		String read;
		StringBuilder sb = new StringBuilder();
		try {
			
				read = sock.read();
				
		} catch (IOException e) {
			throw new ClientException(ErrorCode.E_301, command.getName()
					+ " data faild");
		}
		// sock.close();
		return read;
	}
}
